<?php
namespace app\admin\model;


use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Exception;
use think\facade\Db;
use think\facade\Filesystem;

require_once root_path().'/extend/qiniu/autoload.php';
class MyUpFile
{
    protected $config =[
        'serverurl'=>'/uploads',

    ];
    public function __construct($config=[])
    {
        if($config){
            foreach ($config as $key=>$value){
                $this->config[$key] = $value;
            }
        }
    }

    /**静态上传图片
     * @param array $name
     * @return array
     */
    static public function addFiles($type='图片',$iskey=false,$getid=true,$path=null){
        $obj = new MyUpFile();
        $file = request()->file();
        $newshuju = [];
        if(!empty($file)){
                foreach ($file as $key=>$value){
                    if($getid){
                        if($iskey){
                            $newshuju[$key] =  $obj->getid($obj->addfile($value,$path),$type);
                        }else{
                            $newshuju[] =  $obj->getid($obj->addfile($value,$path),$type);
                        }
                    }else{
                        if($iskey){
                            $newshuju[$key] =  $obj->addfile($value,$path);
                        }else{
                            $newshuju[] =  $obj->addfile($value,$path);
                        }
                    }
                }
        }else{
//            return 2;
            $data = request()->param();
            foreach ($data as $key=>$value){
                if($value){
                    if($getid){
                        if($iskey){
                            $newshuju[$key] = $obj->getid($obj->base64UpFile($value),$type);
                        }else{
                            $newshuju[] = $obj->getid($obj->base64UpFile($value),$type);
                        }
                    }else{
                        if($iskey){
                            $newshuju[$key] = $obj->base64UpFile($value);
                        }else{
                            $newshuju[] = $obj->base64UpFile($value);
                        }
                    }
                }
            }
        }
        return $newshuju;
    }

    /**获取enclosure的id
     * @param $data
     * @param string $type
     * @param string $fenmian
     * @return mixed
     * @throws \think\Exception
     */
    public function getid($data,$type='图片',$fenmian=''){
        $data['type'] = $type;
        if($type!=='图片'&&$fenmian){
            $data['fenmian'] = $fenmian;
        }
        if(!($data['quan_path']??null)){
            $data['quan_path'] = $data['path'];
            if(!strstr($data['path'],'http')){
                $data['quan_path'] = request()->domain().$data['path'];
            }
        }
        $data['create_time'] = time();
        $data['status'] = 1;
        if($data['id'] = Db::name(getTable('enclosure'))->insertGetId($data)){
            return $data;
        }
        return $data;
    }

    /**base64文件上传
     * @param $files
     * @return bool
     */
    public function base64UpFile($files){
        $file = $files['base64'];
        if(preg_match('/^(data:\s*image\/(\w+);base64,)/',$file,$result)){
            $types = explode('.',$files['name']);
            $type = end($types);
            $file_name = uniqid().'.'.$type;
            if(!is_dir('.'.rtrim($this->config['serverurl'],'/').'/'.date('Ymd',time()))){
                chmod('.'.rtrim($this->config['serverurl'],'/').'/',0777);
                mkdir('.'.rtrim($this->config['serverurl'],'/').'/'.date('Ymd',time()));
            }
            $path =$this->config['serverurl'].'/'.date('Ymd',time()).'/'.$file_name;
            $str =explode(',',$file);
            if(file_put_contents('.'.$path,base64_decode($str[1]))){
                $data['path'] = $path;
                $data['yuan_name'] = $files['name'];
                $data['new_name'] = $file_name;
                if($this->isQiNiu()){
                    $data = $this->saveQiNiu($data);
                }
                return $data;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    /**base64上传到七牛云
     * @param $data
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function saveQiNiu($data){
        return $data;
        $qiniu = $this->isQiNiu();
        $ak = $qiniu['ak'];
        $sk = $qiniu['sk'];
        $bucket = $qiniu['bucket'];
        $auth = new Auth($ak,$sk);
        $uploadMgr = new UploadManager();
        $filePath = '.'.$data['path'];
        $token = $auth->uploadToken($bucket,$data['new_name']);
        list($ret,$err) = $uploadMgr->putFile($token,$data['new_name'],$filePath);
        if($err!==null){
            return false;
        }else{
            chmod($filePath,0777);
            if(is_file($filePath)){
                unlink($filePath);
            }
            $data['path'] =  $qiniu['url'].'/'.$data['new_name'];
        }
        return $data;
    }
    //文件上传
    public function addfile($file,$path=null){
        $data = $this->fileServer($file,$path);
        return $data;
    }

    /**文件上传到服务器
     * @param $file
     * @return mixed
     */
    public function fileServer($file,$path){
        $data['yuan_name'] ='';
        $data['path'] = $this->config['serverurl'];
        if(empty($path)){
            $savename = Filesystem::disk('public')->putFile('',$file);
        }else{
            $savename = Filesystem::disk('public')->putFile($path,$file);
        }
        $data['new_name'] = str_replace(date('Ymd').'\\','',$savename);
        if(empty($path)){
            $data['path'] = str_replace('\\','/','/storage/'.$savename);
            $data['quan_path'] = str_replace('\\','/','/storage/'.$savename);
        }else{
            $data['path'] = str_replace('\\','/','/storage/'.$savename);
            $data['quan_path'] = str_replace('\\','/','/storage/'.$savename);
        }
        if(isQiNiu()){
            $data['path'] = $this->fileQiNiu('.'.$data['path'],$data['new_name']);
            $data['quan_path'] = $data['path'];
        }
        return $data;
    }

    /**文件上传到七牛云
     * @param $file
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function fileQiNiu($filePath,$name){
        $qiniu = $this->isQiNiu();
        $ak = $qiniu['ak'];
        $sk = $qiniu['sk'];
        $bucket = $qiniu['bucket'];
        $auth = new Auth($ak,$sk);
        $uploadMgr = new UploadManager();
        $token = $auth->uploadToken($bucket,$name);
        list($ret,$err) = $uploadMgr->putFile($token,$name,$filePath);
        if($err!==null){
            return false;
        }
        if(is_file($filePath)){
            chmod($filePath,0777);
            unlink($filePath);
        }
        $data = str_replace("\\","/",$qiniu['url'].'/'.$name);
        return $data;
    }



    /**检测是否使用七牛云
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function isQiNiu(){
        $status = Db::name(getTable('systems'))
            ->where('id',8)
            ->find();
        if($status['value']!=1){
            return false;
        }
        $url  = Db::name(getTable('systems'))
            ->where('id',4)
            ->find();
        $data['url'] = $url['value'];
        $bucket = Db::name(getTable('systems'))
            ->where('id',5)
            ->find();
        $data['bucket'] = $bucket['value'];
        $ak = Db::name(getTable('systems'))
            ->where('id',6)
            ->find();
        $data['ak'] = $ak['value'];
        $sk = Db::name(getTable('systems'))
            ->where('id',7)
            ->find();
        $data['sk'] = $sk['value'];
        return $data;
    }

    /**删除数据
     * @param $id
     * @param bool $istrue
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function deleteId($id,$istrue=false){
        $data = Db::name(getTable('enclosure'))
            ->where('id','in',$id)
            ->select()->toArray();
        $obj = new MyUpFile();
        foreach ($data as $value){
            if($istrue){
                $obj->deletepath($value['path']);
                Db::name(getTable('enclosure'))
                    ->where('id',$value['id'])
                    ->delete();
            }else{
                Db::name(getTable('enclosure'))
                    ->where('id',$value['id'])
                    ->update(['status'=>0]);
            }
        }
        return true;
    }

    /**根据路径删除文件
     * @param $path
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function deletepath($path){
        if(!strstr($path,'http')){
            if(is_file('.'.$path)){
                chmod('.'.$path,0777);
                unlink('.'.$path);
            }
        }else{
            $path = explode('/',$path);
            $path = end($path);
            $qiniu = $this->isQiNiu();
            $ak = $qiniu['ak'];
            $sk = $qiniu['sk'];
            $bucket  = $qiniu['bucket'];
            $auth = new Auth($ak,$sk);
            $bucketManager = new \Qiniu\Storage\BucketManager($auth);
            $bucketManager->delete($bucket,$path);
        }
        return true;
    }
    /**分片上传图片
     * @return mixed
     */
    static public function FenPians($getid=true,$type='图片'){
        usleep(5000);
        $data = request()->param();
        if($data['hebin']??null){
            $data = MyUpFile::myhebin();
            if($data['wc']){
                $newdata['new_name'] = $data['newname'];
                $newdata['path'] = $data['path'];
                $newdata['yuan_name'] = $data['name'];
                if($getid){
                    $obj = new MyUpFile();
                    $newdata = $obj->getid($newdata,$type,$data['fenmian']??null);
                    $data['id'] = $newdata['id'];
                }
                return $data;
            }
            return $data;
        }
        $name = $data['name'];
        $names = explode('.',$name);
        $names = $names[0];
        $path ='./storage/temp/'.$names.'/'.date('Ymd');
        $npath  = $path;
        $path = $path.'/'.$names.'_'.$data['index'].'.part';
        $newname = $names.'_'.$data['index'].'.part';
        $file = request()->file('file');
        $savename = Filesystem::disk('public')->putFile('temp/'.$names,$file);
        $savename = './storage/'.str_replace('\\','/',$savename);
        try{
            rename($savename,$path);
        }catch (Exception $e){
            chmod($savename,0777);
            rename($savename,$path);
        }
        $done = true;
        $names = explode('.',$data['name']);
        $names = $names[0];
        for($a=1;$a<=(int)$data['number'];$a++){
            if(!file_exists($npath.'/'.$names.'_'.$a.'.part')){
                $done = false;
            }
        }
//        return $npath.$names;
        $data['success'] = 0;
        if($done){
            $data['success'] = 1;
            return $data;
        }
        return $data;
    }
    /**FenPians配套的合并函数
     * @return mixed
     */
    static public function myhebin(){
        $data = request()->param();
        $start = $data['start']??1;
        $name = explode('.',$data['name']);
        $type = end($name);
//        $data['newname'] = $name[0];
//        $data['wc'] = true;
        if(!(isset($data['newname'])&&$data['newname'])){
            $data['newname'] =uniqid().'.'.$type;
        }
        $filepath = '/storage/'.date('Ymd');
        $path = './storage/temp/'.$name[0].'/'.date('Ymd');
        $unsetdir = './storage/temp/'.$name[0];
        if(!is_dir('.'.$filepath)){
            mkdir('.'.$filepath,0777);
        }
        $data['wc'] = false;
        for($a=0;$a<10;$a++){
            if(is_file($path.'/'.$name[0].'_'.$start.'.part')){
                chmod($path.'/'.$name[0].'_'.$start.'.part',0777);
                $str = file_get_contents($path.'/'.$name[0].'_'.$start.'.part');
                file_put_contents('.'.$filepath.'/'.$data['newname'],$str,FILE_APPEND);
                unlink($path.'/'.$name[0].'_'.$start.'.part');
            }else{
                $data['wc'] = true;
                $data['path'] = $filepath.'/'.$data['newname'];
                rmdir($path);
                break;
            }
            $start++;
        }
        if($data['wc']){
//            $data['name'] = $unsetdir;
            if(is_dir($unsetdir)){
                rmdir($unsetdir);
            }
//            deldir($unsetdir);
        }
        $data['start'] = $start;
        return $data;
    }
}